package cn.demomaster.quickui_sample.ui.fragment.helper;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static androidx.core.content.ContextCompat.getExternalFilesDirs;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.demomaster.quickcompat.util.QDFileUtil;
import com.demomaster.quickcompat.util.QuickThread;
import com.demomaster.quickcompat.view.loading.LoadingCircleView;
import com.demomaster.quickcompat.widget.button.QuickButton;
import com.demomaster.quickcompat.widget.dialog.QuickActionDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickpermission.QuickPermission;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import cn.demomaster.quickui.annotation.ActivityPager;
import cn.demomaster.quickui.annotation.ResType;
import cn.demomaster.quickui_sample.R;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;

/**
 * Squirrel桓
 * 2018/8/25
 */
@ActivityPager(name = "文件管理", preViewClass = TextView.class, resType = ResType.Custome)
public class FileManagerFragment extends QuickFragment {

    //Components
    QuickButton btn_search;
    QuickButton btn_delete;
    TextView tv_current;

    @NonNull
    @Override
    public View onGenerateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_layout_filemanager, null);
        return mView;
    }

    public void initView(View rootView) {

        btn_search = findViewById(R.id.btn_search);
        btn_delete = findViewById(R.id.btn_delete);
        tv_current = findViewById(R.id.tv_current);
        getActionBarTool().setTitle("文件管理");
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        btn_search.setOnClickListener(v -> {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    String rootPath = Environment.getExternalStorageDirectory().getPath();
                    List<File> files = QDFileUtil.getEmptyFiles(rootPath);
                    for (File f : files) {
                        QdLog.d(f);
                    }
                }
            });
            thread.start();
        });
        btn_delete.setOnClickListener(v -> {
            count = 0;
            QuickPermission.with(getActivity()).permissions(new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE})
                    .onGranted(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            QuickActionDialog quickActionDialog = new QuickActionDialog.Builder(mContext).setContentView(new LoadingCircleView(mContext)).setContentbackgroundColor(mContext.getResources().getColor(cn.demomaster.quickrouter.R.color.transparent_dark_cc)).setBackgroundRadius(50).setTopImage(cn.demomaster.quickui.R.mipmap.quickdevelop_ic_launcher).setMessage("删除中...").create();
                            quickActionDialog.show();
                            btn_delete.setEnabled(false);
                            String rootPath = Environment.getExternalStorageDirectory().getPath();
                           /* File file = new File("/");
                            if(file!=null){
                                deleteEmptyFiles(file.getAbsolutePath());
                            }else {
                                deleteEmptyFiles(rootPath);
                            }*/

                            //deleteEmptyFiles(rootPath);
                            deleteEmptyFiles(QDFileUtil.getStoragePath(mContext, true));

                            btn_delete.setEnabled(true);
                            btn_delete.setText("删除文件");
                            quickActionDialog.dismiss();
                            return null;
                        }
                    }).request();
        });

        List<String> sdcards = QDFileUtil.getExtSDCardPathList();
        if (sdcards != null) {
            for (String sdcard : sdcards) {
                QdLog.println("sdcards:" + sdcard);
            }
        }

        File[] files;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            files = getExternalFilesDirs(mContext, Environment.MEDIA_MOUNTED);
            for (File file : files) {//便历所有外部存储
                QdLog.println("main", "外部存储：" + file.getAbsolutePath());
            }
        }

        QdLog.println("StoragePath:", android.os.Environment.getExternalStorageDirectory().getPath());
        QdLog.println("StoragePath:", QDFileUtil.getStoragePath(mContext, true));
        QdLog.println("getExternalStorageState:", Environment.getExternalStorageState());
        QdLog.println("getExternalCacheDir=" + getContext().getExternalCacheDir().getAbsolutePath());
        QdLog.println("getFilesDir=" + getContext().getFilesDir().getAbsolutePath());
        QdLog.println("getCacheDir=" + getContext().getCacheDir().getAbsolutePath());
        QdLog.println("getExternalStorageDirectory=" + android.os.Environment.getExternalStorageDirectory().getAbsolutePath());
        // QdLog.i("getExternalStoragePublicDirectory="+android.os.Environment.getExternalStoragePublicDirectory().getAbsolutePath());
        // QdLog.i("getExternalFilesDir="+getContext().getExternalFilesDir().getAbsolutePath());
        QdLog.println("getExternalStorageDirectory=" + getContext().getExternalCacheDir().getAbsolutePath());
        QdLog.println("getExternalCacheDir=" + getContext().getExternalCacheDir().getAbsolutePath());
        QdLog.println("getRootDirectory=" + android.os.Environment.getRootDirectory().getAbsolutePath());


        QdLog.println("getExternalFilesDir=" + mContext.getExternalFilesDir("").getParentFile().getAbsolutePath());
        QdLog.println("FilesDir().getParentFile()=" + mContext.getFilesDir().getParentFile().getAbsolutePath());

        String path = Environment.getExternalStorageDirectory() + File.separator + "tsetfile.txt";
        QdLog.d(path);
        File file = new File(path);
        QDFileUtil.createFile(file);
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//        getFileCreatTime(file, qdFile -> {
//            if (qdFile != null) {
//                Date date = new Date(qdFile.getModifyTime());
//                QdLog.println("文件修改时间：" + simpleDateFormat.format(date));
//            }
//        });


    }

    private int count;
    private void deleteEmptyFiles(String rootPath) {
        //String rootPath = Environment.getExternalStorageDirectory().getPath() ;
        File file = new File(rootPath);
        if (file.isDirectory()) {
            if (file.listFiles() == null) {
                QdLog.println("文件不存在:" + file.getPath());
                return;
            }
            if (Objects.requireNonNull(file.listFiles()).length == 0) {
                count += 1;
                QuickThread.runOnUiThread(() -> tv_current.setText("正在删除第" + count + "空文件夹:" + file.getPath()));
                QdLog.e("删除第(" + count + ")空文件夹[" + (QDFileUtil.delete(file.getPath()) ? "成功" : "失败") + "]:" + file.getPath());
                return;
            }
            QdLog.d("文件夹:" + file.getPath() + "，文件个数(" + Objects.requireNonNull(file.listFiles()).length + ")");
            for (File file1 : Objects.requireNonNull(file.listFiles())) {
                deleteEmptyFiles(file1.getPath());
            }
        }
    }

    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        ((Activity)getContext()).startActivityForResult(Intent.createChooser(i, "上传文件"), 0);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                if (null != uploadFile) {
                    Uri result = data == null ? null
                            : data.getData();
                    uploadFile.onReceiveValue(result);
                    uploadFile = null;
                }
                if (null != uploadFiles) {
                    Uri result = data == null ? null
                            : data.getData();
                    uploadFiles.onReceiveValue(new Uri[]{result});
                    uploadFiles = null;
                }
            } else if (resultCode == RESULT_CANCELED) {
                if (null != uploadFile) {
                    uploadFile.onReceiveValue(null);
                    uploadFile = null;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}